package com.fintech.pangu.security.oauth2.sso.client.session;

import com.alibaba.fastjson.JSON;
import com.fintech.pangu.commons.enums.BusinessEnum;
import com.fintech.pangu.security.oauth2.sso.client.model.dto.SystemInfoDto;
import com.fintech.pangu.security.oauth2.sso.client.model.vo.SystemInfoResponse;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义Session过期策略
 * 返回前端json，让前端通知授权服务器logout
 */
@Getter
@Setter
public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    private String authServerLogoutUri;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        HttpServletResponse response = event.getResponse();

        SystemInfoDto systemInfoDto = new SystemInfoDto();
        systemInfoDto.setAuthServerLogoutUri(authServerLogoutUri + "/logout?isNoticeOtherClient=false");

        SystemInfoResponse systemInfoResponse = SystemInfoResponse
                .builder()
                .systemInfo(systemInfoDto)
                .build();
        systemInfoResponse.setRetCode(BusinessEnum.SSO_USER_LOGOUT.getCode());
        systemInfoResponse.setRetDesc(BusinessEnum.SSO_USER_LOGOUT.getMessage());

        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(systemInfoResponse));
        out.flush();
        out.close();
    }

}
